<template>
  <div class="login">
    <!-- 暂留左边栏 -->
    <!-- <div class="left">
      <img src="../assets/logo/logo.jpg" alt="">
    </div> -->
    <!-- 右边栏 -->
    <div class="right">
      <div class="login-form">
        <WeChatLogin :showQrCode="showQrCode" @showQrCodeChange="showQrCodeChange"></WeChatLogin>
        <!-- 标题 -->
        <h3 class="title">
          <img src="../../assets/logo/logo.jpg" alt="" class="logo">
          {{ title }}
        </h3>
        <div v-if="!showQrCode">
          <!-- 切换登录方式 -->
          <el-tabs v-model="activeName" type="card">
            <!-- 账号登录 -->
            <el-tab-pane label="账号登录" name="first">
              <!-- 表单 -->
              <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
                <!-- 用户名 -->
                <el-form-item prop="username">
                  <!-- 用户名输入框 -->
                  <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
                    <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
                  </el-input>
                </el-form-item>
                <!-- 密码 -->
                <el-form-item prop="password">
                  <!-- 密码输入框 -->
                  <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
                    @keyup.enter.native="handleLogin">
                    <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
                  </el-input>
                </el-form-item>
                <!-- 验证码 -->
                <el-form-item prop="code" v-if="captchaEnabled">
                  <!-- 验证码输入框 -->
                  <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
                    @keyup.enter.native="handleLogin">
                    <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
                  </el-input>
                  <!-- 验证码图片 -->
                  <div class="login-code">
                    <img :src="codeUrl" @click="getCode" class="login-code-img" />
                  </div>
                </el-form-item>
                <!-- 记住密码 -->
                <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
                <!-- 登录按钮 -->
                <el-form-item style="width:100%;">
                  <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
                    @click.native.prevent="handleLogin">
                    <span v-if="!loading">登 录</span>
                    <span v-else>登 录 中...</span>
                  </el-button>
                  <div style="float: right;" v-if="register">
                    <router-link class="link-type" :to="'/register'">立即注册</router-link>
                  </div>
                </el-form-item>
              </el-form>

            </el-tab-pane>
            <el-tab-pane label="验证码登录" name="second">
              <el-form ref="phoneForm" :model="phoneForm" :rules="phoneRules">
                <!-- 手机号 -->
                <el-form-item prop="phone">
                  <!-- 手机号输入框 -->
                  <el-input v-model="phoneForm.phone" type="text" auto-complete="off" placeholder="手机号">
                    <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
                  </el-input>
                </el-form-item>
                <!-- 验证码 -->
                <el-form-item prop="phoneCode" v-if="captchaEnabled">
                  <!-- 验证码输入框 -->
                  <el-input v-model="phoneForm.phoneCode" auto-complete="off" placeholder="验证码" style="width: 50%"
                    @keyup.enter.native="handleLogin">
                    <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
                  </el-input>
                  <el-button :disabled="isCounting" @click="startCountdown" type="primary"
                    style="font-size: 12px;margin-left: 10px;">
                    {{ buttonText }}
                  </el-button>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item style="width:100%;">
                  <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
                    @click.native.prevent="handlePhoneLogin">
                    <span v-if="!loading">登 录</span>
                    <span v-else>登 录 中...</span>
                  </el-button>
                  <div style="float: right;" v-if="register">
                    <router-link class="link-type" :to="'/register'">立即注册</router-link>
                  </div>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-else>
          <div class="qrcode">
            <p class="qr-tip">请使用微信扫一扫登录</p>
            <div id="login_container">

            </div>
          </div>
        </div>
      </div>
    </div>
    <!--  底部  -->
    <!-- <div class="el-login-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div> -->
  </div>
</template>
<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import WeChatLogin from './components/weChatLogin.vue'

export default {
  name: "Login",
  components: { WeChatLogin },
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      phoneForm: {
        phone: '',
        phoneCode: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      phoneRules: {
        phone: [
          // 必填规则
          {
            required: true,
            trigger: "change",
            message: "请输入手机号"
          },
          // 格式校验规则
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, // 支持+86和0086前缀
            trigger: "blur",
            message: "请输入合法的手机号"
          }
        ],
        phoneCode: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      activeName: 'first',
      showQrCode: false,
      countdown: 0,     // 当前剩余时间
      timer: null,      // 定时器ID
      isCounting: false // 是否正在倒计时
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  mounted() {
    // 动态创建 script 标签
    // const script = document.createElement('script')
    // script.src = 'http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
    // script.onload = () => {
    //   // 确保脚本加载完成后执行相关逻辑
    //   window.ExternalSDK.init()
    // }
    // document.head.appendChild(script)
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path:'/product/index'}).catch(() => { });
            // this.$router.push({ path: this.redirect || '/product' }).catch(() => { });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    },
    async showQrCodeChange() {
      let redirect_URL = encodeURIComponent(window.location.origin + "/wxlogin");
      // let result = await reqWxLogin(redirect_URL);
      let result = {}
      //生成微信扫码登录二维码页面
      //@ts-ignore
      // new WxLogin({
      //   self_redirect: true, //true:手机点击确认登录后可以在 iframe 内跳转到 redirect_uri
      //   id: "login_container", //显示二维码容器设置
      //   appid: result.data.appid, //应用位置标识appid
      //   scope: "snsapi_login", //当前微信扫码登录页面已经授权了
      //   redirect_uri: result.data.redirectUri, //填写授权回调域路径,就是用户授权成功以后，微信服务器向公司后台推送code地址
      //   state: result.data.state, //state就是后台服务器重定向的地址携带用户信息
      //   style: "black",
      //   href: "",
      // });
      this.showQrCode = !this.showQrCode
    },
    startCountdown() {
      if (this.isCounting) return
      this.$refs.phoneForm.validateField('phone', (errorMsg) => {
        if (errorMsg) {
          return
        } else {
          // 初始化倒计时
          this.isCounting = true
          this.countdown = 60

          // 启动定时器
          this.timer = setInterval(() => {
            this.countdown--

            if (this.countdown <= 0) {
              this.resetCountdown()
            }
          }, 1000)
        }
      })
    },
    resetCountdown() {
      clearInterval(this.timer)
      this.isCounting = false
      this.countdown = 0
    },
    // 手机号登录按钮
    handlePhoneLogin() {
      this.$refs.phoneForm.validate(valid => {

      })
    }
  },
  computed: {
    buttonText() {
      return this.isCounting
        ? `${this.countdown} 秒后重新获取`
        : '获取验证码'
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    this.resetCountdown()
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  // align-items: center;
  width: 100%;
  height: 100%;
  background-image: url("../../assets/images/login-background.jpg");
  background-size: cover;
}

// .left{
//   width: 50%;
//   display: flex;
//   align-items: center;
//   justify-content: center;
// }
.right {
  // width: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.title {
  margin: 0px auto 30px auto;
  // text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #707070;

  .logo {
    width: 50px;
    height: 20px;
    text-align: center;
  }
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

.qrcode {
  width: 100%;
  height: 300px;
  background: #fff;
}

.qr-tip {
  text-align: center;
  color: #999;
  margin: 0;
}
</style>
